﻿using System;
using System.Runtime.Caching;

namespace Common
{
    /// <summary>
    /// 缓存对象帮助类  lc  2014年10月16日15:44:06
    /// </summary>
    public static class CacheHelper
    {
        /// <summary>
        /// 根据CacheId,获得对应的cache对象。
        /// </summary>
        /// <param name="CacheId"></param>
        /// <returns></returns>
        static public object GetCache(string CacheId)
        {
            //获得对应的Cache object 对象。
            ObjectCache oCache = MemoryCache.Default;
            object objCache = oCache[CacheId];
            return objCache;
        }

        /// <summary>
        /// 寫入 Cache 資料 ( 預設 60*10 秒 默认绝对过期)
        /// </summary>
        /// <param name="CacheId">缓存Key</param>
        /// <param name="objCache">缓存对象</param>
        static public void SetCache(string CacheId, object objCache, bool sliding = false)
        {
            if (sliding)
                SetCacheBySliding(CacheId, objCache, 60 * 10);
            else
                SetCacheByAbsolute(CacheId, objCache, 60 * 10);
        }

        /// <summary>
        /// 设置缓存信息,绝对过期
        /// </summary>
        /// <param name="CacheId">缓存唯一Key</param>
        /// <param name="objCache">缓存对象</param>
        /// <param name="cacheDurationSeconds">缓存时间</param>
        static public void SetCacheByAbsolute(string CacheId, object objCache, int cacheDurationSeconds)
        {
            if (objCache != null)
            {
                ObjectCache oCache = MemoryCache.Default;
                oCache.Set(CacheId, objCache, new DateTimeOffset(new DateTime(), new TimeSpan(0, 0, cacheDurationSeconds)));
                //插入缓存对象
            }
        }
        /// <summary>
        /// 设置缓存信息,滑动过期
        /// </summary>
        /// <param name="CacheId">缓存唯一Key</param>
        /// <param name="objCache">缓存对象</param>
        /// <param name="cacheDurationSeconds">缓存时间</param>
        static public void SetCacheBySliding(string CacheId, object objCache, int cacheDurationSeconds)
        {
            if (objCache != null)
            {
                ObjectCache oCache = MemoryCache.Default;
                CacheItemPolicy policy=new CacheItemPolicy();
                policy.SlidingExpiration = new TimeSpan(0, 0, cacheDurationSeconds);
                oCache.Set(CacheId, objCache,policy);
                //插入缓存对象
               
            }
        }
    }
}
